<template>
  <el-container>
    <el-header style="padding: 0;">
      <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false"
        background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" @select="handleSelect">
        <el-menu-item index="0" @click="goToHome">
          <img style="width: 100px" alt="logo" />
        </el-menu-item>
        <el-menu-item index="1" @click="goToMain">尝试搜索</el-menu-item>
        <el-sub-menu index="2">
          <template #title>用户名</template>
          <el-menu-item index="2-1" @click="goToInfo">用户中心</el-menu-item>
          <el-menu-item index="2-2" @click="logout">退出</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-header>
    <div style="padding:30px">
    <companimate/>
    </div>
    <el-container style="width: 80%;margin: auto;">
      
      <el-main style="padding: 0; padding-right: 10px; ">
        <el-card style="border-radius: 30px;">
          <!-- 分类筛选部分 -->
          <div class="filter-section">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-select v-model="selectedCategory" placeholder="选择分类" @change="filterWords">
                  <el-option
                    v-for="category in categories"
                    :key="category"
                    :label="category"
                    :value="category"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索关键词"
                  @input="filterWords"
                  clearable
                ></el-input>
              </el-col>
              <el-col :span="7" style="font-size: 15px;display: flex;">
                <span style="margin: auto;">左侧为种子词，右侧为最佳竞争词</span>
                </el-col>
            </el-row>
          </div>

          <!-- 筛选结果部分 -->
          <div class="result-section">
            <el-card
              v-for="word in filteredWords"
              :key="word.word"
              class="word-card"
            >
              {{ word.word }} : {{ word.compKeyword }}
            </el-card>
            <div v-if="filteredWords.length === 0" class="no-results">
              暂无符合条件的结果
            </div>
          </div>
        </el-card>
      </el-main>
      <el-aside width="200px" class="aside-container">
        <div class="hot-words-section">
          <h3 style="color: black;">热词排行榜</h3>
          <el-card v-for="(word, index) in hotWords" :key="index" class="hot-word-card">
            <span >{{ index + 1 }}. {{ word.word }}</span>
            <el-tag>{{word.num}}次搜索</el-tag>
          </el-card>
        </div>
      </el-aside>
    </el-container>
  </el-container>
</template>

<script>
import axios from "axios"; // 导入 axios
import companimate from "./companimate.vue"

export default {
  name: 'Home',
  components: {
        companimate,
    },
  data() {
    return {
      categories: ["所有","科技", "生活", "教育", "娱乐"], // 分类数据
      words: [
        { word: "人工智能", category: "科技" , compKeyword: "1"},
        { word: "区块链", category: "科技" , compKeyword: "2" },
        { word: "健康养生", category: "生活" , compKeyword: "3" },
        { word: "家庭教育", category: "教育" , compKeyword: "4" },
        { word: "电影", category: "娱乐" , compKeyword: "5" },
        { word: "音乐", category: "娱乐" , compKeyword: "6" },
      ],
      selectedCategory: "", // 当前选择的分类
      searchKeyword: "", // 搜索关键词
      filteredWords: [],
      hotWords: [
        { word: "奔驰", num: 3 },
        { word: "戴尔", num: 2 },
        { word: "苹果", num: 1 },
        { word: "联想", num: 0 }
      ], // 热词数据
    };
  },
  methods: {
    goToMain() {
      this.$router.push({ name: 'Main' })
    },
    goToInfo() {
        this.$router.push({ name: 'Info' })
    },
    goToHome() {
      this.$router.push({ name: 'Home' })
    },
    filterWords() {
      const keyword = this.searchKeyword.trim().toLowerCase();

      if (this.selectedCategory === "所有") {
        this.filteredWords = this.words.filter((item) => {
          const matchesKeyword = keyword
            ? item.word.toLowerCase().includes(keyword)
            : true;
          return matchesKeyword;
        });
      } else {
        this.filteredWords = this.words.filter((item) => {
          const matchesCategory = this.selectedCategory
            ? item.category === this.selectedCategory
            : true;
          const matchesKeyword = keyword
            ? item.word.toLowerCase().includes(keyword)
            : true;
          return matchesCategory && matchesKeyword;
        });
      }
    },

    async fetchWords() {
      try {
        const response = await axios.get('http://localhost:8090/api/tag/keyword');
        const data = response.data;

        // 将接口返回的数据映射成所需结构
        this.words = [
          {
            word: data.keywords.seedKeyword,
            category: data.tag.tagName || "其他",
            compKeyword: data.recommend, // 添加 compKeyword
          },
        ];

        // 提取分类数据并去重
        const categoriesSet = new Set();
        this.words.forEach((item) => {
          if (item.category) {
            categoriesSet.add(item.category);
          }
        });

        this.categories = ["所有", ...Array.from(categoriesSet)];
        this.filterWords(); // 初始化筛选结果
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    },


    async fetchRankingData() {
      try {
        const response = await axios.get("http://localhost:8090/api/ranking/system");
        const rankingData = response.data.data;

        // 提取 seedKeyword 和 searchNum，并排序
        this.hotWords = rankingData
          .map((item) => ({
            word: item.seedKeyword, // 关键词
            num: item.searchNum,    // 搜索次数
          }))
          .sort((a, b) => b.num - a.num); // 按搜索次数降序排序

      } catch (error) {
        console.error("获取热词排行榜失败:", error);
      }
    },

  },
  mounted() {
    // 初始化时显示所有结果
    this.filteredWords = this.words.map((item) => item.word);
    this.fetchKeywords(); // 页面加载时调用接口
  },
}
</script>

<style scoped>
.home {
  text-align: center;
  margin-top: 50px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
}

.el-menu--horizontal>.el-menu-item:nth-child(1) {
  margin-right: auto;
}

.filter-section {
  margin-bottom: 20px;
}
.result-section {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.word-card {
  padding: 10px;
  width: calc(25% - 10px);
  text-align: center;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.no-results {
  text-align: center;
  color: #909399;
  font-size: 14px;
  margin-top: 20px;
}

.hot-words-section {
  background: #aaa;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.hot-words-section h3 {
  font-size: 16px;
  margin-bottom: 10px;
  text-align: center;
}
.hot-word-card {
  margin-bottom: 10px;
  border-radius: 5px;
  text-align: left;
  display: flex;
  flex-direction: column;
}
</style>